package com.blrs.controller;

import java.util.*;
import java.util.stream.Collectors;
import javax.servlet.http.HttpServletResponse;

import com.blrs.VO.ClassVO;
import com.blrs.common.annotation.RepeatSubmit;
import com.blrs.common.core.domain.entity.SysDept;
import com.blrs.common.utils.SecurityUtils;
import com.blrs.common.utils.StringUtils;
import com.blrs.domain.QualificationInfo;
import com.blrs.domain.vo.BusinessMainClassVo;
import com.blrs.service.enterprise.seas.IHighSeasService;
import com.blrs.system.service.ISysDeptService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import com.blrs.common.annotation.Log;
import com.blrs.common.core.controller.BaseController;
import com.blrs.common.core.domain.AjaxResult;
import com.blrs.common.enums.BusinessType;
import com.blrs.domain.HighSeas;
import com.blrs.common.utils.poi.ExcelUtil;
import com.blrs.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 公海管理Controller
 * 
 * @author ruoyi
 * @date 2023-08-08
 */
@RestController
@RequestMapping("/highSeas/seas")
public class HighSeasController extends BaseController
{
    @Autowired
    private IHighSeasService highSeasService;
    @Autowired
    private ISysDeptService sysDeptService;
    /**
     * 查询公海管理列表
     */
    //@PreAuthorize("@ss.hasPermi('highSeas:seas:list')")
    @GetMapping("/list")
    public TableDataInfo list(HighSeas highSeas)
    {
        startPage();
       if (SecurityUtils.getUserId()!=1 && SecurityUtils.getUserId()!=2){
           highSeas.setBelongTo(SecurityUtils.getOrgId());
       }
        List<HighSeas> list = highSeasService.selectHighSeasList(highSeas);
        return getDataTable(list);
    }
    /**
     * 查询公海管理前15条记录
     */
    @GetMapping("/listByIndex")
    public List listByIndex(){
         List<HighSeas> list = highSeasService.selectHighSeasListByIndex(SecurityUtils.getOrgId());
         return list;
    }
    /**
     * 查询当前企业所有公海数据的信息来源
     */
    @GetMapping("/listSource")
    public List<String> listSource(){
        return highSeasService.selectSourceByBelongTo(SecurityUtils.getOrgId());
    }

    /**
     * 导出公海管理列表
     */
    //@PreAuthorize("@ss.hasPermi('highSeas:seas:export')")
    @Log(title = "公海管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @RepeatSubmit(interval = 3000,message = "导出操作过于频繁，请稍后再试")
    public void export(HttpServletResponse response, HighSeas highSeas)
    {
        highSeas.setBelongTo(SecurityUtils.getOrgId());
        List<HighSeas> list = highSeasService.selectHighSeasList(highSeas);
        ExcelUtil<HighSeas> util = new ExcelUtil<HighSeas>(HighSeas.class);
        util.exportExcel(response, list, "公海管理数据");
    }

    /**
     * 获取公海管理详细信息
     */
    //@PreAuthorize("@ss.hasPermi('highSeas:seas:query')")
    @GetMapping(value = "/{enterpriseId}")
    public AjaxResult getInfo(@PathVariable("enterpriseId") String enterpriseId)
    {
        return success(highSeasService.selectHighSeasByEnterpriseId(enterpriseId));
    }

    /**
     * 新增公海管理
     */
    //@PreAuthorize("@ss.hasPermi('highSeas:seas:add')")
    @Log(title = "公海管理", businessType = BusinessType.INSERT)
    @RepeatSubmit(interval = 3000,message = "新增操作过于频繁，请稍后再试")
    @PostMapping
    public AjaxResult add(@RequestBody HighSeas highSeas)
    {
        try {
            return highSeasService.insertHighSeas(highSeas);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 修改公海管理
     */
    //@PreAuthorize("@ss.hasPermi('highSeas:seas:edit')")
    @Log(title = "公海管理", businessType = BusinessType.UPDATE)
    @PutMapping
    @RepeatSubmit(interval = 3000,message = "修改操作过于频繁，请稍后再试")
    public AjaxResult edit(@RequestBody HighSeas highSeas) throws NoSuchFieldException, IllegalAccessException {
       return highSeasService.updateHighSeas(highSeas);
    }

    /**
     * 删除公海管理
     */
    //@PreAuthorize("@ss.hasPermi('highSeas:seas:remove')")
    @Log(title = "公海管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{enterpriseIds}")
    public AjaxResult remove(@PathVariable String[] enterpriseIds)
    {
        return toAjax(highSeasService.deleteHighSeasByEnterpriseIds(enterpriseIds));
    }
    /**
     * 企业信息转公海
     */
    //@PreAuthorize("@ss.hasPermi('highSeas:seas:add')")3
    @Log(title = "公海管理",businessType = BusinessType.INSERT)
    @PostMapping("/convert")
    public AjaxResult convert(@RequestBody String[] enterId){
        return highSeasService.convertHighSeas(enterId);
    }
    /**
     * 导出公海管理模板
     */
    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {

        ExcelUtil<HighSeas> util = new ExcelUtil<>(HighSeas.class);
        util.importTemplateExcel(response, "公海管理数据");
    }

    @Log(title = "导入公海管理", businessType = BusinessType.IMPORT)
    //@PreAuthorize("@ss.hasPermi('qualificationInfo:qualification:import')")
    @PostMapping("/importData")
    @RepeatSubmit(interval = 3000,message = "导出操作过于频繁，请稍后再试")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<HighSeas> util = new ExcelUtil(HighSeas.class);
        List<HighSeas> list = util.importExcel(file.getInputStream());
        // 过滤非空数据并去重（按 enterpriseName 字段去重）
        List<HighSeas> uniqueList = list.stream()
                .filter(Objects::nonNull)
                .filter(item -> StringUtils.isNotEmpty(item.getEnterpriseName())) // 确保 enterpriseName 非空
                .collect(Collectors.collectingAndThen(
                        Collectors.toMap(HighSeas::getEnterpriseName, item -> item, (existing, replacement) -> existing),
                        map -> new ArrayList<>(map.values())
                ));
        if (StringUtils.isEmpty(uniqueList)){
            return AjaxResult.error("导入失败，请检查文档");
        }
        return highSeasService.importExcel(uniqueList);
    }
    @Log(title = "批量修改主分类", businessType = BusinessType.UPDATE)
    //@PreAuthorize("@ss.hasPermi('qualificationInfo:qualification:import')")
    @PostMapping("/updateClass")
    public AjaxResult updateClass(@RequestBody ClassVO classVO) throws Exception
    {
        highSeasService.updateClassIds(classVO.getEnterIds(),classVO.getClassId());
        return success("修改成功");
    }

    @PostMapping("/editBusinessManager")
    public AjaxResult editBusinessManager(@RequestBody ClassVO classVO) {
        return toAjax(highSeasService.editBusinessManager(classVO));
    }

    /**
     * 分页查询所有组织机构
     */
    //@PreAuthorize("@ss.hasPermi('system:dept:list')")
    @GetMapping("/orgList")
    public TableDataInfo orgList(SysDept dept){
        startPage();
        List<SysDept> list=sysDeptService.selectOrgList(dept);
        return getDataTable(list);
    }

    /**
     * 根据归属于获取当前公海最新编号
     * @return
     */
    @GetMapping(value = "/getMaxEnterpriseNo")
    public String getMaxEnterpriseNo(){
        return highSeasService.getMaxEnterpriseNo(SecurityUtils.getOrgId());
    }

}
